<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;

class User extends Controller
{

    public function index()
    {
        //原生
        $list = Db::query("select * from user;");
        //Db
        $list = Db::table('lover')->order(['id'=>'desc'])->select();
        //助手函数
        $list = db('user')->field(['id','name'])->select();
        dump($list);
    }
    public function insert()
    {
        //原生
        $result = Db::execute("insert into user (id,name,age) values(null,'k1','18')");
        //准备数据
        $data = [
            "name" => 'K4',
            "age" => '48'
        ];
        //DB
        //$result = Db::table('user')->insert($data);
        //$result = Db::table('user')->insertGetId($data);

        //助手函数
        $result = db('user')->insert($data);
        var_dump($result);
    }

    public function delete()
    {
        //原生
        //$result = Db::execute("delete from user where name='k3'");
        //DB
        //$result = Db::table('user')->delete(49);
        //$result = Db::table('user')->where('name','K1')->delete();
        //助手函数
        $result = db('user')->delete(49);
        var_dump($result);
    }
    public function update()
    {
        //原生
        //$result = Db::execute("update user set age = '19' where id='1'");
        //DB
        //$result = Db ::table('user')->where('id','1')->update(['age'=>'99']);
        //助手函数
        $result = db('user')->where('id',1)->update(['age'=>'19']);
        var_dump($result);
    }
    public function sw()
    {
        // Db::transaction(function(){
        //     $userdata = ['name' => '吕布','age' => '35','sex' => '1'];
        //     $id = Db::table('user')->insertGetId($userdata);
        //     var_dump('用户的ID:' .$id);
        //
        //     $loverdata = ['name' => '貂蝉','sex' => '2','user_id' => $id];
        //     Db::table('lover')->insert($loverdata);
        //     return '关系建立完成....';
        // });
        Db::startTrans();
        try{
            $userdata = ['name' =>'刘备','age'=>'38','sex'=>'1'];
            $id = Db::table('user')->insertGetId($userdata);
            var_dump('用户的ID:' .$id);

            $loverdata = ['name'=>'小乔','sex'=>'0','user_id'=>$id];
            Db::table('lover')->insert($loverdata);
            Db::commit();
            return '关系建立完成...';
        } catch(\Exception $e){
            return '关系建立完成...';
            Db::rollback();
        }
    }
}
